package com.lhframework.socket.thread;

import com.alibaba.fastjson.JSON;
import com.lhframework.socket.model.RealTrack;
import com.lhframework.socket.repository.RealTrackRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by lh on 2017/8/14.
 */
public class RealTrackThread extends Thread {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RealTrackRepository trackRepository;

    private static BlockingQueue<RealTrack> realTracksQueue = new LinkedBlockingQueue<>();

    public void init(){
        start();
    }

    public static void put(RealTrack realTrack) {
        try {
            realTracksQueue.put(realTrack);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static RealTrack take() {
        try {
            return realTracksQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int size() {
        return realTracksQueue.size();
    }

    @Override
    public void run() {
        while (true) {
            try {
                RealTrack realTrack = realTracksQueue.take();
                logger.info("存储队列轨迹数据>>>>>" + JSON.toJSONString(realTrack));
                trackRepository.save(realTrack);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
